package ch.rouge66.energymonitor.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

public abstract class GenericDaoImpl<T extends Entity> implements GenericDao<T> {

	private Class<T> clazz;

	@SuppressWarnings("unchecked")
	public GenericDaoImpl() {  
		   this.clazz = (Class<T>) this.getClass();
	     } 

   public T create(T entity) {
	   Long id = (Long) getSession().save(entity);
	   entity.setId(id);
	   return entity;
	}
	
	@SuppressWarnings("unchecked")
	public T readById(Long id) {
		return (T) getSession().get(clazz, id);
	}
	
	public void update(T entity) {
	    getSession().update(entity);
	}
	
	public void delete(T entity) {
	    getSession().delete(entity);
	}
	
    @SuppressWarnings("unchecked")
	public List<T> readByQuery(Query query) {
        List<T> t;
        t = query.list();
        return t;
    }
 
    @SuppressWarnings("unchecked")
	public List<T> readAll() {
        List<T> t = null;
        Query query = getSession().createQuery("from " + clazz.getName());
        t = query.list();
        return t;
    }
	
    protected Session getSession() {
        return EntityManager.getSession();
    }

}